	package com.example.filemanager;

import java.io.File;
import java.util.ArrayList;
	
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
	/**
	 * 
	 * *java课程设计
	 * 安卓文件资源管理器
	 * @author 兰兴舟，张金伟，齐畅，叶金蕾
	 * 
	 * 
	 */
	public class Search extends ListActivity {
	    private ArrayList<String> FileName = null;
	    private ArrayList<String> FilePath = null;
	    private static final String ROOT_PATH = "/";
	    private static String NOW_PATH;
	    //重命名布局xml文件显示dialog
	    private View view;
	    private EditText editText;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		FilePath = SearchDirOrFile(getIntent().getStringExtra("path"),getIntent().getStringExtra("filename"));
		ShowSDir(FilePath);
	}
	/**
	 * 显示搜索结果
	 * @param sfilepath
	 */
	private void ShowSDir(ArrayList<String> sfilepath){
		FileName = new ArrayList<String>();
		for(String p : sfilepath ){
			File f = new File(p);
			FileName.add(f.getName());
		}
		this.setListAdapter(new MyAdapter(this, FileName, sfilepath));
	}
	/**
	 * 多线程搜索文件
	 * @param path
	 * @param filename
	 * @return ArrayList<String>
	 */
/*	private ArrayList<String> SearchDirOrFile(String path,String filename) {
		ArrayList<String> sresult = new ArrayList<String>();
		File file = new File(path);
		if(file.isDirectory()){
			SearchThread search = new SearchThread(file,filename);
			FutureTask<ArrayList<String>> task = new FutureTask<ArrayList<String>>(search);
			new Thread(task).start();
			try {
				for (String f : task.get()) {
					sresult.add(f);
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return sresult;
	 }
*/	
	
	/**
	 * 单线程搜索文件
	 * @param path
	 * @param filename
	 * @return ArrayList<String>
	 */
	private ArrayList<String> SearchDirOrFile(String path,String filename){
		ArrayList<String> result=new ArrayList<String>();
		File file = new File (path);
		File[] files = file.listFiles();
			if(file.exists()&&files!=null){
				for(File f :files){
					if(f.getName().equals(filename)){
						result.add(f.getPath());
					}if(f.isDirectory()){
						ArrayList<String> mresult= SearchDirOrFile(f.getPath(),filename);
						result.addAll(mresult);
					}
				}
			}
		return result;	
	}
	/**
	 * 显示文件夹
	 * @param path
	 */
	private void showFileDir(String path) {
        FileName = new ArrayList<String>();
        FilePath = new ArrayList<String>();
        File file = new File(path);
        NOW_PATH = path;

        File[] files = file.listFiles();
        //添加所有文件
        for (File f : files) {
            FileName.add(f.getName());
            FilePath.add(f.getPath());
        }
        this.setListAdapter(new MyAdapter(this, FileName, FilePath));
    }
	
	/**
     * 点击事件
     * @param l
     * @param v
     * @param position
     * @param id
     */
	protected void onListItemClick(ListView l, View v, int position, long id) {
        String path = FilePath.get(position);
        File file = new File(path);
        // 文件存在并可读
        if (file.exists() && file.canRead()) {
            if (file.isDirectory()) {
                //显示子目录及文件
                showFileDir(path);
            } else {
                //处理文件
                fileHandle(file);
            }
        }
        //没有权限
        else {
            Resources res = getResources();
            new AlertDialog.Builder(this).setTitle("提示")
                    .setMessage(res.getString(R.string.no_permission))
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(getApplicationContext(), "没有权限", Toast.LENGTH_SHORT).show();
                        }
                    }).show();
        }
        super.onListItemClick(l, v, position, id);
    }

	/**
	 * 文件处理
	 * @param file
	 */
    private void fileHandle(final File file) {
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            @SuppressWarnings("deprecation")
			@Override
            public void onClick(DialogInterface dialog, int which) {
                // 打开文件
                if (which == 0) {
                    openFile(file);
                }
                //重命名
                else if (which == 1) {
                    LayoutInflater factory = LayoutInflater.from(Search.this);
                    view = factory.inflate(R.layout.rename_dialog, null);
                    editText = (EditText) view.findViewById(R.id.editText);
                    editText.setText(file.getName());

                    DialogInterface.OnClickListener listener2 = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            String modifyName = editText.getText().toString();
                            final String fpath = file.getParentFile().getPath();
                            final File newFile = new File(fpath + "/" + modifyName);
                            if (newFile.exists()) {
                                //排除没有修改情况
                                if (!modifyName.equals(file.getName())) {
                                    new AlertDialog.Builder(Search.this)
                                            .setTitle("注意!")
                                            .setMessage("文件名已存在，是否覆盖？")
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    if (file.renameTo(newFile)) {
                                                        showFileDir(fpath);
                                                        displayToast("重命名成功！");
                                                    } else {
                                                        displayToast("重命名失败！");
                                                    }
                                                }
                                            })
                                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {

                                                }
                                            })
                                            .show();
                                }
                            } else {
                                if (file.renameTo(newFile)) {
                                    showFileDir(fpath);
                                    displayToast("重命名成功！");
                                } else {
                                    displayToast("重命名失败！");
                                }
                            }
                        }
                    };
                    AlertDialog renameDialog = new AlertDialog.Builder(Search.this).create();
                    renameDialog.setView(view);
                    renameDialog.setButton("确定", listener2);
                    renameDialog.setButton2("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                        }
                    });
                    renameDialog.show();
                }
                //拷贝文件
                else if (which == 2){
                	Intent intent = new Intent(Search.this,Copy.class);
                	intent.putExtra("soupath", file.getPath());
                	startActivity(intent);
                }
                //删除文件
                
                else {
                    new AlertDialog.Builder(Search.this)
                            .setTitle("注意!")
                            .setMessage("确定要删除此文件吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (file.delete()) {
                                        //更新文件列表
                                        showFileDir(file.getParent());
                                        displayToast("删除成功！");
                                    } else {
                                        displayToast("删除失败！");
                                    }
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).show();
                }
            }
        };
        //选择文件时，弹出操作选项对话框
        String type = getMIMEType(file);
        String[] menu = {"打开文件", "重命名", "拷贝","删除文件",};
        if(type=="text"){
        	menu[0] = "预览";
        }

        
        new AlertDialog.Builder(Search.this)
                .setTitle("请选择要进行的操作!")
                .setItems(menu, listener)
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
    }

    /**
     * 打开文件
     * @param file
     */
    private void openFile(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        String type = getMIMEType(file);
        if(type.equals("text")){
        	intent = new Intent(Search.this,Preview.class); 
        	intent.putExtra("path", file.getPath());
        	}
        else{
        	type += "/*";
        	intent.setDataAndType(Uri.fromFile(file), type);
        	}
        startActivity(intent);
        
    }

    /**
     * 获取文件mimetype
     * @param file
     * @return
     */
	private String getMIMEType(File file) {
        String type = "";
        String name = file.getName();
        //文件扩展名
        String end = name.substring(name.lastIndexOf(".") + 1, name.length()).toLowerCase();
        if (end.equals("m4a") || end.equals("mp3") || end.equals("wav")) {
            type = "audio";
        } else if (end.equals("mp4") || end.equals("3gp")||end.equals("avi")) {
            type = "video";
        } else if (end.equals("jpg") || end.equals("png") || end.equals("jpeg") || end.equals("bmp") || end.equals("gif")) {
            type = "image";
        } else if(end.equals("txt") || end.equals("java") || end.equals("ini") || end.equals("bat")){
        	type = "text";
        }
        else {
            //如果无法直接打开，跳出列表由用户选择
            type = "*";
        }
//        type += "/*";
        return type;
    }
	/**
	 * 显示消息
	 * @param message
	 */
    private void displayToast(String message) {
        Toast.makeText(Search.this, message, Toast.LENGTH_SHORT).show();
    }
    

}
